import psutil
import json
import datetime

from flask_script import commands

from app.machines.mac import MacInfo
import subprocess
import platform

class CpuInfo:
    """
    CPU信息获取
    """
    def get_cpu_info():
        cpu_dic = {}
        # 利用率
        utilization = psutil.cpu_percent(interval=0.0)
        # 速度 也叫当前频率 current_freq
        speed = 0.0
        # 最小频率 min_freq
        min_speed = 0.0
        # 基准速度，也叫最大频率max_freq
        base_speed = 0.0

        # 频率
        freq_list = psutil.cpu_freq()

        if len(freq_list):
            speed = freq_list[0]
            min_speed = freq_list[1]
            base_speed = freq_list[2]


        # print(speed)
        # print(min_speed)
        # print(base_speed)

        # 进程
        processes = len(psutil.pids())
        # print(processes)


        # print(psutil.boot_time())
        # 开机时间
        start_machine_time_str = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
        # print(start_machine_time_str)

        # 逻辑处理器数量
        logical_processors = psutil.cpu_count()
        # print(logical_processors)

        # 内核数
        kernels = psutil.cpu_count(logical=False)
        # print(kernels)

        # 句柄数
        process = psutil.Process()
        handles = 0
        threads = 0
        for id in psutil.pids():
            try:
                p = psutil.Process(id)
                handles += p.num_handles()
                threads += p.num_threads()
            except:
                print("psutil.NoSuchProcess: psutil.NoSuchProcess no process found with pid" + str(id))

        # 线程数
        # threads = process.num_threads()
        cpu_dic['mac_code'] = MacInfo.get_mac()
        cpu_dic['utilization'] = utilization
        cpu_dic['logical_processors'] = logical_processors
        cpu_dic['speed'] = speed
        cpu_dic['base_speed'] = base_speed
        cpu_dic['processes'] = processes
        cpu_dic['start_machine_time_str'] = start_machine_time_str
        cpu_dic['logical_processors'] = logical_processors
        cpu_dic['kernels'] = kernels
        cpu_dic['handles'] = handles
        cpu_dic['threads'] = threads

        return cpu_dic

if __name__ == '__main__':
    # cpus = CpuInfo.get_cpu_info()
    # json.dumps(dict)将dict转成str
    # cpu_json = json.dumps(cpus)
    # print(cpu_json)
    commands